package com.adinnet.admin.child.service.impl;

import com.adinnet.admin.child.model.Child;
import com.adinnet.admin.child.mapper.ChildMapper;
import com.adinnet.admin.child.model.form.ChildForm;
import com.adinnet.admin.child.model.form.ChildRankForm;
import com.adinnet.admin.child.model.vo.ChildRank;
import com.adinnet.admin.child.model.vo.ChildReq;
import com.adinnet.admin.child.model.vo.ChildResp;
import com.adinnet.admin.child.service.ChildService;
import com.adinnet.admin.user.mapper.UserMapper;
import com.adinnet.admin.user.model.User;
import com.adinnet.common.sms.response.SmsSendResponse;
import com.adinnet.common.sms.util.ChuangLanSmsUtil;
import com.adinnet.common.utils.DateUtil;
import com.adinnet.common.utils.MD5Util;
import com.adinnet.core.JsonResult;
import com.adinnet.core.PageResult;
import com.adinnet.core.exception.BizException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 儿童表 服务实现类
 * </p>
 *
 * @author zYshuai
 * @since 2020-12-11
 */
@Service
public class ChildServiceImpl extends ServiceImpl<ChildMapper, Child> implements ChildService {

    private Logger log = LoggerFactory.getLogger("ChildServiceImpl");


    @Autowired
    private ChildMapper childMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public PageResult<ChildRank> queryRankList(ChildRankForm form) {
        Page<ChildRank> page = new Page<>(form.getPage(), form.getLimit());
        List<ChildRank> list = baseMapper.queryRankList(page, form);
        return new PageResult<>(list, page.getTotal());
    }

    @Override
    public PageResult<ChildResp> queryChildList(ChildForm childForm) {
        Page<ChildResp> page = new Page<>(childForm.getPage(), childForm.getLimit());
        List<ChildResp> list = baseMapper.queryChildList(page, childForm);
        return new PageResult<>(list, page.getTotal());
    }

    @Override
    @Transactional
    public Integer addNewChild(ChildReq childReq) {
        //2021-06-15 体验学员默认一个月的体验时长，一个月体验过后账号将不能登陆app学习
        Date date = DateUtil.addMonthDate(new Date(), 1);
        String psw = MD5Util.MD5("a123456", "UTF-8");
        User user = new User();
        Child c = new Child();
        BeanUtils.copyProperties(childReq,user);
        BeanUtils.copyProperties(childReq,c);
        user.setPwd(psw);
        user.setType(1);
        if(null!=childReq.getStudentType()&&childReq.getStudentType()==2){
            user.setLastExperienceTime(date);
        }
        userMapper.insert(user);
        //初始的账号默认的段位为1
        c.setUserId(user.getId());
        c.setPeaseLevelId(1);
        c.setRankLevelId(1);
        childMapper.insert(c);
        if(c.getId()!=null) {
            String msg = "亲爱的用户，您的默认登陆密码为：a123456，感谢注册！";
            SmsSendResponse smsSendResponse = ChuangLanSmsUtil.sendCommonSms(childReq.getTelNo(), msg);
            if (!smsSendResponse.getCode().equals("0")) {
                //短信经常会因为ip限制和其他外部原因发送失败，这里短信发送失败还是让正常注册，不影响流程
                //throw new BizException("注册失败,发送短信失败");
                log.info("用户{}发送注册短信失败",user.getId());
            }
        }
        return c.getId();
    }

    @Override
    @Transactional
    public Integer editChild(ChildReq childReq) {
        //2021-06-15 体验学员默认一个月的体验时长，一个月体验过后账号将不能登陆app学习
        Date date = DateUtil.addMonthDate(new Date(), 1);
        String psw = MD5Util.MD5("a123456", "UTF-8");
        Child child = childMapper.selectById(childReq.getChildId());
        User user = userMapper.selectById(child.getUserId());
        //新建修改实体,不用再插入userId
        User u = new User();
        Child c = new Child();
        BeanUtils.copyProperties(childReq,u);
        BeanUtils.copyProperties(childReq,c);
        u.setId(user.getId());
        if(null!=childReq.getStudentType()&&childReq.getStudentType()==2){
            u.setLastExperienceTime(date);
        }
        c.setId(child.getId());
        if(!user.getTelNo().equals(childReq.getTelNo())){
            User ou=userMapper.selectOne(new QueryWrapper<User>().eq("tel_no",childReq.getTelNo()).eq("deleted", 0));
            if(ou!=null){
                throw new BizException("编辑失败,手机号已存在注册用户");
            }
            u.setPwd(psw);
            String msg = "亲爱的用户，您的登陆手机号已变更，默认登陆密码重置为：a123456，，感谢使用！";
            SmsSendResponse smsSendResponse = ChuangLanSmsUtil.sendCommonSms(childReq.getTelNo(), msg);
            if (!smsSendResponse.getCode().equals("0")) {
                //throw new BizException("编辑失败,发送短信失败");
                log.info("用户{}发送变更注册手机号短信失败",user.getId());
            }
        }
        userMapper.updateById(u);
        childMapper.updateById(c);
        return c.getId();
    }

    @Override
    public JsonResult deleteIds(String childIds) {
        childMapper.deleteIds(childIds);
        userMapper.deleteChilds(childIds);
        return JsonResult.ok("操作成功");
    }
}
